package cc.dowell.controller;

import cc.dowell.enums.HttpCodeEnum;
import cc.dowell.vo.echart.Option;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cc.dowell.config.ContextHolder;
import cc.dowell.dto.HistoryDto;
import cc.dowell.pojo.Fruit;
import cc.dowell.pojo.History;
import cc.dowell.service.FruitService;
import cc.dowell.service.HistoryService;
import cc.dowell.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/history")
public class HistoryController {

    @Autowired
    private HistoryService historyService;

    @Autowired
    private FruitService fruitService;

    // @Autowired
    // private HistoryMapper historyMapper;

    @Value("${custom-setting.server-host}")
    String serverIp;

    @Value("${custom-setting.file-path.root}")
    String rootPath;

    @Value("${custom-setting.file-path.img-detected}")
    String imgDetectedPath;


    @GetMapping("/{pageNum}/{pageSize}")
    public R<?> list(@PathVariable long pageNum,
                     @PathVariable long pageSize,
                     @RequestParam(defaultValue = "") String beginDate,
                     @RequestParam(defaultValue = "")  String endDate,
                     @RequestParam(defaultValue = "")  String varietyCode) {
        Page<History> page = new Page<>(pageNum, pageSize);
        IPage<History> historyPage = historyService.selectHistoryPage(page,beginDate,endDate,varietyCode);
        return R.success(historyPage);
    }

    @GetMapping("/{id}")
    public R<?> getHistoryById(@PathVariable("id") long id){
        History history = historyService.getById(id);
        return R.success(history);
    }

    @PostMapping()
    public R<?> add(@RequestBody HistoryDto historyDto) {
        //Base64
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(historyDto.getImgBase64());
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            String savePath = rootPath + imgDetectedPath;
            File savePathFile = new File(savePath);
            //不存在则创建文件夹
            if (!savePathFile.exists()) {
                savePathFile.mkdirs();
            }
            String suffix = ".jpg";
            //新文件名字防止重复加上UUID
            String newFileName = UUID.randomUUID() + suffix;
            //新的文件路径
            String newFileFullPath = savePath + newFileName;
            log.info("detectedFileSavePath:" + newFileFullPath);
            File newFile = new File(newFileFullPath);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
            bos.write(bytes);
            bos.flush();
            bos.close();
            //创建历史记录的实例
            History history = new History();
            BeanUtils.copyProperties(historyDto,history);
            //设置图片的路径
            history.setImgPath("/img2/"+newFileName);
            //设置创建者ID
            Long userId = ContextHolder.getUserId();
            history.setCreateUserId(userId);
            //设置与code相关联的fruitId
            //根据品种码（VarietyCode）进行查询
            Fruit fruit = fruitService.selectFruitByCode(history.getVarietyCode());
            if(fruit!=null){
                history.setFruitId(fruit.getId());
                //保存 history
                Boolean b = historyService.save(history);
                if(b){
                    return R.success(HttpCodeEnum.DETECT_FINISH);
                }else{
                    return R.error(HttpCodeEnum.DETECT_FAIL);
                }
            }else{
                //无法识别的品种
                return R.error(HttpCodeEnum.DETECT_EXCEPTION);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @GetMapping ("/getCountByMonth")
    public R getCountByMonth() throws Exception {
        Option option = historyService.getCountByMonth();
        if(option!=null){
            return R.success(option);
        }
        return R.error();
    }

    @GetMapping ("/getCountByVariety")
    public R getCountByVariety() throws Exception {
        Option option = historyService.getCountByVariety();
        if(option!=null){
            return R.success(option);
        }
        return R.error();
    }

    @GetMapping ("/getMatureRate")
    public R getMatureRate() throws Exception {
        Option option = historyService.getMatureRate();
        if(option!=null){
            return R.success(option);
        }
        return R.error();
    }





}
